package com.ymatou.iapi.sellerproduct.testcase;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.sellerproduct.service.AddNewSellerProductCall;
import com.ymatou.iapi.sellerproduct.service.UpdateStockBySkuCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.database.mongo.ProductDetailModelWapper;
import com.ymttest.database.mongo.YmtMongoDriverFactroy;
import com.ymttest.database.mongo.jproduct.CatalogsWapper;
import com.ymttest.database.sqlwapper.YmtCatalogsIWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.JsonBeanHelper;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.TestDataManager;

public class Ts_UpdateStockBySku {
	public static UpdateStockBySkuCall updateStockBySkuCall = new UpdateStockBySkuCall();
	public static AddNewSellerProductCall addNewSellerProductCall = new AddNewSellerProductCall();
	private static Integer sellerId = 3383;
	private static String sellerName = EnvSetup.getData("productsellername");	
	
	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("商品改规格库存");
	}
	
	@Before
	public void caseUp() {
		
	}
	
	@AfterClass
	public static void tearDown() {
		Logger.generateResult(updateStockBySkuCall.getOpurl());
	}
	
	@After
	public void caseDown() {
		Logger.end();
	}
	
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_UpdateStockBySku_001() {
		Logger.start(true,"修改多个SKU的库存，并多次修改");
		try{
			JSONObject addProductBean = JsonBeanHelper.getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc10.json");	
			JsonBeanHelper.updateJsonBean(addProductBean, MapUtil.hashMap("UserID", sellerId,"LoginID", sellerName));
			List<String> skuList = generateSKUList(8);
			setSkuForAddProduct(skuList,addProductBean);
			
			//发布商品 带SKU
			String productId = addNewSellerProductCall.callAndGetReturnData(addProductBean).getJSONObject("Data").getString("ProductID");
			Logger.comment("ProductId: " + productId);
			
			
			//修改stock
			Map<String,Object> skuAndStockMap = generateSKUStock(skuList);
			JSONObject retBean = updateStockBySkuCall.update(sellerId, skuAndStockMap);
			Logger.verifyEquals(200, retBean.getInt("Code"), "返回code检查");
			
			checkStockBySku(retBean.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap);
			
			
			//修改stock
			Map<String,Object> skuAndStockMap1 = generateSKUStock(skuList);
			JSONObject retBean1 = updateStockBySkuCall.update(sellerId, skuAndStockMap1);
			Logger.verifyEquals(200, retBean1.getInt("Code"), "返回code检查");
			
			checkStockBySku(retBean1.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap1);
			
			
			//修改stock
			Map<String,Object> skuAndStockMap2 = generateSKUStock(skuList);
			JSONObject retBean2 = updateStockBySkuCall.update(sellerId, skuAndStockMap2);
			Logger.verifyEquals(200, retBean2.getInt("Code"), "返回code检查");
			
			checkStockBySku(retBean2.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap2);
			
		}catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_UpdateStockBySku_002() {
		Logger.start(true,"修改相同SKU的库存");
		try{
			JSONObject addProductBean = JsonBeanHelper.getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc10.json");	
			JsonBeanHelper.updateJsonBean(addProductBean, MapUtil.hashMap("UserID", sellerId,"LoginID", sellerName));
			List<String> skuList = generateSKUList(1);
			
			
			List<String> skuList2 = new ArrayList<>();
			skuList2.add(skuList.get(0));
			skuList2.add(skuList.get(0));
			setSkuForAddProduct(skuList2,addProductBean);
			
			//发布商品 带SKU 重复
			String productId = addNewSellerProductCall.callAndGetReturnData(addProductBean).getJSONObject("Data").getString("ProductID");
			Logger.comment("ProductId: " + productId);
			
			
			//修改stock
			Map<String,Object> skuAndStockMap = generateSKUStock(skuList);
			int stock = Integer.parseInt(skuAndStockMap.get(skuList.get(0)).toString());
			JSONObject retBean = updateStockBySkuCall.update(sellerId, skuAndStockMap);
			Logger.verifyEquals(200, retBean.getInt("Code"), "返回code检查");
			
			YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
			List<Map> retList = ymtCatalogsIWapper.selectProductIdBySku(skuList.get(0));
			
			Map<String,Object> ret1 = retList.get(0);
			Map<String,Object> ret2 = retList.get(1);
			int actStockInSql1 = Integer.parseInt(ret1.get("iNum").toString());
			int actStockInSql2 = Integer.parseInt(ret2.get("iNum").toString());
			
			
			Logger.verifyEquals(true , ((actStockInSql1==stock)&&(actStockInSql2!=stock))||((actStockInSql1!=stock)&&(actStockInSql2==stock)), "SKU: " +skuList.get(0)+ ",只能修改一个对应的SKU" );
			
		}catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_UpdateStockBySku_003() {
		Logger.start(true,"一次性修改超过11个SKU的库存");
		try{
			JSONObject addProductBean = JsonBeanHelper.getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc10.json");	
			JsonBeanHelper.updateJsonBean(addProductBean, MapUtil.hashMap("UserID", sellerId,"LoginID", sellerName));
			List<String> skuList = generateSKUList(8);
			setSkuForAddProduct(skuList,addProductBean);
			
			//发布商品 带SKU
			String productId = addNewSellerProductCall.callAndGetReturnData(addProductBean).getJSONObject("Data").getString("ProductID");
			Logger.comment("ProductId: " + productId);
			
			
			//修改stock
			Map<String,Object> skuAndStockMap = generateSKUStock(skuList);
			JSONObject retBean = updateStockBySkuCall.update(sellerId, skuAndStockMap);
			Logger.verifyEquals(200, retBean.getInt("Code"), "返回code检查");
			
			checkStockBySku(retBean.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap);
			
			//设置11个skulist
			List<String> new_skuList = generateSKUList(3);
			new_skuList.addAll(skuList);
			Map<String,Object> skuAndStockMap1 = generateSKUStock(new_skuList);
			JSONObject retBean1 = updateStockBySkuCall.update(sellerId, skuAndStockMap1);
			Logger.verifyEquals(400, retBean1.getInt("Code"), "返回code检查");
			
			//超过11个，修改失败，所以第一次修改的库存没有变化
			checkStockBySku(retBean.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap);
			
		}catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_UpdateStockBySku_004() {
		Logger.start(true,"修改非该买手SKU的库存");
		try{
			JSONObject addProductBean = JsonBeanHelper.getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc10.json");	
			JsonBeanHelper.updateJsonBean(addProductBean, MapUtil.hashMap("UserID", sellerId,"LoginID", sellerName));
			List<String> skuList = generateSKUList(8);
			setSkuForAddProduct(skuList,addProductBean);
			
			//发布商品 带SKU
			String productId = addNewSellerProductCall.callAndGetReturnData(addProductBean).getJSONObject("Data").getString("ProductID");
			Logger.comment("ProductId: " + productId);
			
			
			//正常修改stock
			Map<String,Object> skuAndStockMap = generateSKUStock(skuList);
			JSONObject retBean = updateStockBySkuCall.update(sellerId, skuAndStockMap);
			Logger.verifyEquals(200, retBean.getInt("Code"), "返回code检查");
			checkStockBySku(retBean.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap);
			
			//非该买手 修改stock
			Map<String,Object> skuAndStockMap2 = generateSKUStock(skuList);
			JSONObject retBean2 = updateStockBySkuCall.update(12312, skuAndStockMap2);
			Logger.verifyEquals(200, retBean2.getInt("Code"), "返回code检查");
			JSONArray SkuResults = retBean2.getJSONObject("Data").getJSONArray("SkuResults");
			for (int i=0;i<SkuResults.length();i++){
				Logger.verifyEquals(false,SkuResults.getJSONObject(i).getBoolean("ExecSuccess"),"SKU:"+SkuResults.getJSONObject(i).getString("SkuId")+" 应修改失败");
			}
			
			
			//非该买手修改失败，所以第一次修改的库存没有变化
			checkStockBySku(retBean.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap);
			
			
		}catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_UpdateStockBySku_005() {
		Logger.start(true,"SKU库存值 不为数字");
		try{
			JSONObject addProductBean = JsonBeanHelper.getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc10.json");	
			JsonBeanHelper.updateJsonBean(addProductBean, MapUtil.hashMap("UserID", sellerId,"LoginID", sellerName));
			List<String> skuList = generateSKUList(8);
			setSkuForAddProduct(skuList,addProductBean);
			
			//发布商品 带SKU
			String productId = addNewSellerProductCall.callAndGetReturnData(addProductBean).getJSONObject("Data").getString("ProductID");
			Logger.comment("ProductId: " + productId);
			
			
			//修改stock
			Map<String,Object> skuAndStockMap = generateSKUStock(skuList);
			JSONObject retBean = updateStockBySkuCall.update(sellerId, skuAndStockMap);
			Logger.verifyEquals(200, retBean.getInt("Code"), "返回code检查");
			
			checkStockBySku(retBean.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap);
			
			//修改stock为String
			Map<String,Object> retMap = new HashMap<>();
			skuList.forEach(ele->{
				retMap.put(ele, "ssss");
				Logger.comment("SKU: "+ ele+", stock: "+"ssss" );
			});
			
			JSONObject retBean1 = updateStockBySkuCall.update(sellerId, retMap);
			Logger.verifyEquals(200, retBean1.getInt("Code"), "返回code检查");
			
			
			//stock非数字，所以都变为0
			skuAndStockMap.forEach((x,y)->{
				skuAndStockMap.put(x, 0);
			});
			checkStockBySku(retBean.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap);
			
			
			
		}catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_UpdateStockBySku_006() {
		Logger.start(true,"修改不存在的SKU");
		try{
			List<String> skuList = generateSKUList(8);
			Map<String,Object> skuAndStockMap = generateSKUStock(skuList);

			JSONObject retBean = updateStockBySkuCall.update(sellerId, skuAndStockMap);
			Logger.verifyEquals(200, retBean.getInt("Code"), "返回code检查");
			
			JSONArray SkuResults = retBean.getJSONObject("Data").getJSONArray("SkuResults");
			for (int i=0;i<SkuResults.length();i++){
				Logger.verifyEquals(false,SkuResults.getJSONObject(i).getBoolean("ExecSuccess"),"SKU:"+SkuResults.getJSONObject(i).getString("SkuId")+" 应修改失败");
			}
		}catch(Exception e){
			Logger.fail(e);
		}
	}
	
	@Test
	@Category({P1.class})
	@TestCase
	public void Tc_UpdateStockBySku_007() {
		Logger.start(true,"修改部分存在，部分不存在的SKU");
		try{
			JSONObject addProductBean = JsonBeanHelper.getJsonBean("com.ymatou.iapi.sellerproduct/AddNewSellerProduct/AddNewProductTpl_Tc10.json");	
			JsonBeanHelper.updateJsonBean(addProductBean, MapUtil.hashMap("UserID", sellerId,"LoginID", sellerName));
			List<String> skuList = generateSKUList(4);
			
			//部分存在，部分不存在
			List<String> skuList2 = generateSKUList(4);
			
			setSkuForAddProduct(skuList,addProductBean);
			
			//发布商品 带SKU
			String productId = addNewSellerProductCall.callAndGetReturnData(addProductBean).getJSONObject("Data").getString("ProductID");
			Logger.comment("ProductId: " + productId);
			
			
			//正常修改 部分存在，部分不存在SKU
			Map<String,Object> skuAndStockMap = generateSKUStock(skuList);
			Map<String,Object> skuAndStockMap2 = generateSKUStock(skuList2);
			skuAndStockMap2.putAll(skuAndStockMap);
			JSONObject retBean = updateStockBySkuCall.update(sellerId, skuAndStockMap2);
			Logger.verifyEquals(200, retBean.getInt("Code"), "返回code检查");
			JSONArray SkuResults = retBean.getJSONObject("Data").getJSONArray("SkuResults");
			for(int i=0;i<SkuResults.length();i++){
				if (skuList2.contains(SkuResults.getJSONObject(i).getString("SkuId"))){
					Logger.verifyEquals(false,SkuResults.getJSONObject(i).getBoolean("ExecSuccess"),"SKU:"+SkuResults.getJSONObject(i).getString("SkuId")+" 应修改失败");
				}
			}
			
			
			checkStockBySku(retBean.getJSONObject("Data").getJSONArray("SkuResults"),skuAndStockMap);
		}catch(Exception e){
			Logger.fail(e);
		}
	}
	
	
	
	
	public static List<String> generateSKUList(int num){
		List<String> skuList = new ArrayList<>();
		for (int i=0;i<num;i++){
			skuList.add("SKU"+TestDataManager.getRandomIntNum(10));
		}
		return skuList;
	}

	public static Map<String,Object> generateSKUStock(List<String> skuList){
		Map<String,Object> retMap = new HashMap<>();
		skuList.forEach(ele->{
			int stock = TestDataManager.getRandomIntNum(2);
			retMap.put(ele, stock);
			Logger.comment("SKU: "+ ele+", stock: "+stock );
		});
		return retMap;
	}
	
	
	public static void setSkuForAddProduct(List<String> skuList,JSONObject addProdRequest) throws JSONException{
		JSONArray catalogAry = addProdRequest.getJSONObject("Product").getJSONArray("Catalogs");
		int minNum = Math.min(skuList.size(),catalogAry.length());
		for(int i=0;i<minNum;i++){
			catalogAry.getJSONObject(i).put("SKU", skuList.get(i));
		}
	}
	
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void checkStockBySku(JSONArray skuResults, Map<String,Object> skuIdandStockMap) throws Exception{
		YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
		
		
		for (String skuId : skuIdandStockMap.keySet() ){
			//返回报文检查
			boolean isFoundInRet = false;
			for(int j=0;j<skuResults.length();j++){
				if (skuResults.getJSONObject(j).getString("SkuId").equals(skuId)){
					Logger.verifyEquals(true, skuResults.getJSONObject(j).getBoolean("ExecSuccess"), "ExecSuccess 返回报文检查");
					isFoundInRet = true;
					break;
				}
			}
			Logger.verifyEquals(true, isFoundInRet, "SKU:"+skuId+",在返回报文中是否存在");
			
			
			//期待库存
			int tgtStock = Integer.parseInt(skuIdandStockMap.get(skuId).toString());
			
			List<Map> retList = ymtCatalogsIWapper.selectProductIdBySku(skuId);
			Logger.verifyEquals(1, retList.size(), "SKU:"+skuId+", 应该只有一个对应的catalog");
			Map<String,Object> ret = retList.get(0);
			
			String productId = ret.get("sProductId").toString();
			String catalogId = ret.get("sCatalogId").toString();
			int actStockInSql = Integer.parseInt(ret.get("iNum").toString());
			
			//sql
			Logger.verifyEquals(tgtStock, actStockInSql, "sql中库存检查 catalogId:"+catalogId+", sku:"+skuId);
			
			//mongo
			if (YmtMongoDriverFactroy.isNewMongoCheck()){
				ProductDetailModelWapper productDetailModelWapper = new ProductDetailModelWapper();
				Map<String,Object> dataInMgo = productDetailModelWapper.getProductId(productId);
				JSONArray catalogAry = new JSONArray(dataInMgo.get("CatalogList").toString());
				
				boolean isFound = false;
				for(int i=0;i<catalogAry.length();i++){
					JSONObject catalogBean = catalogAry.getJSONObject(i);
					if (catalogBean.getString("CatalogId").equals(catalogId)){
						Logger.verifyEquals(skuId, catalogBean.getString("SKU"),"Mongo中sku检查 catalogId:"+catalogId+", sku:"+skuId);
						
						JSONArray stockList = catalogBean.getJSONArray("StockList");
						for(int k=0;k<stockList.length();k++){
							if (stockList.getJSONObject(k).getInt("StockType")==0){
								Logger.verifyEquals(tgtStock,stockList.getJSONObject(k).getInt("Stock") , "Mongo中库存检查 catalogId:"+catalogId+", sku:"+skuId);
							}
						}
						
						isFound = true;
						break;
					}
				}
				
				Logger.verifyEquals(true, isFound,  "scatalogId:"+catalogId+", sku:"+skuId+", 应该在mongo库中存在");
			};
			
			
			//java mongo
			if (YmtMongoDriverFactroy.isNewJavaMgoCheck()){
				CatalogsWapper catalogsWapper = new CatalogsWapper();
				Map<String,Object> dataInMgo = catalogsWapper.getByCatalogId(catalogId);
				int actStockInMgo = Integer.parseInt(dataInMgo.get("stock").toString());
				Logger.verifyEquals(skuId, dataInMgo.get("sku").toString(),"Java Mongo中sku检查 catalogId:"+catalogId+", sku:"+skuId);
				Logger.verifyEquals(tgtStock, actStockInMgo, "Java Mongo中库存检查 catalogId:"+catalogId+", sku:"+skuId);
			}
		}
		
		
	}
	
	
	
}

